import asyncio
from http.server import BaseHTTPRequestHandler, HTTPServer

# import template
from router import Router
from middleware import middleware
# from middleware import log_middleware

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel


# TODO: 模版功能开发，可使用Jinja和MOKA
"""
# 定义请求处理函数
def handle_request(request):
    # 处理请求的逻辑
    return "Response"


# 将日志中间件应用到请求处理函数上
handle_request = log_middleware(handle_request)

# 处理请求
response = handle_request(request)

data = {
    'title': 'My Framework',
    'framework': 'Awesome Framework'
}

output = template.render_template('index.html', data)
print(output)
"""

# TODO: 开发Gorse类，用于APP创建
# TODO: 开发Gorse类，类中包含router处理装饰器，用于router配置
# TODO: 开发Gorse类，类中包含对request和response的处理
# TODO: 开发Gorse类，类中包含对JSON的处理，以支持api开发
# TODO: 开发Gorse类，类中包含模版渲染支持选项，可以通过Jinja和moka模板引擎渲染HTML页面
# TODO: 开发Gorse类，用于支持表单处理
# TODO: 开发Gorse类，类中包含middleware的处理装饰器
# TODO: 开发Gorse类，用于支持文件上传和下载处理
# TODO: 开发Gorse类，支持用户自定义启动host，port，debug等
# TODO: 支持使用 uvicorn 或 asyncio 来启动项目
# TODO: 支持异步和非异步使用

# TODO: 开发Error类，用于错误处理

# TODO: 开发Logger类，用于日志输出和打印，以及配置日志保存位置和日志输出级别配置

# TODO: 开发对Cookie参数处理
# TODO: 开发对Header参数处理
# TODO: 开发响应状态码
# TODO: 开发请求文件
# TODO: 开发请求表单和文件

# TODO: 开发Middleware类，用于支持中间件

# TODO: 开发支持类型校验

# TODO: 开发支持对源(CORS)进行配置，比如使用列表：
#  [
#     "http://example.com",
#     "https://example.com",
#     "http://localhost",
#     "http://localhost:8080",
#  ]


class Gorse:
    def __init__(self, host=None, port=8888):
        self.host = host
        self.port = port

    async def handle(self):
        pass

    async def errors(self):
        pass

    async def route(self):
        pass

    async def logger(self):
        pass

    def config(self):
        pass

    def run(self):
        pass

    def middleware(self):
        pass

    @classmethod
    def get(cls, *args, **kwargs):
        def wrapper():
            pass
        pass

    @classmethod
    def post(cls, *args, **kwargs):
        def wrapper():
            pass
        pass


app = Gorse()


class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        response = Router.get_response(self.path)
        # 如果需要解决 emoji 问题，pip install emoji 并使用一下方法
        # response = response.decode('utf-8')
        # response = emoji.demojize(response)
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write(response.encode())


# async def run_server():
#     server_address = ('', 8000)
#     httpd = HTTPServer(server_address, MyHandler)
#     httpd.request_handler = asyncio.coroutine_wrapper(httpd.request_handler, middleware)
#     httpd.serve_forever()


# async def run_server():
#     server_address = ('', 8000)
#     httpd = HTTPServer(server_address, MyHandler)
#     httpd.request_handler = asyncio.create_task(httpd.request_handler, middleware)
#     httpd.serve_forever()


class MyHTTPServer(HTTPServer):
    def __init__(self, server_address, RequestHandlerClass, middleware):
        super().__init__(server_address, RequestHandlerClass)
        self.middleware = middleware

    def handle_request(self):
        self.request_handler = self.middleware(self.request_handler)
        super().handle_request()


async def run_server():
    server_address = ('', 8000)
    httpd = MyHTTPServer(server_address, MyHandler, middleware)
    httpd.serve_forever()

# loop = asyncio.get_event_loop()
# loop.run_until_complete(run_server())

run_server()